package com.strawcom.charmring.util;

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.security.KeyStore;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import android.content.Context;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.util.Log;

public class InputStreamProvider {
	

	
	private static HttpClient httpclient;
	private static HttpPost post;
	private static InputStream is;
	private static OutputStream os;
	private static Context context = null;
	
	static AssetManager am = null;
	
	private static void initContext(Context context){
		am = context.getAssets();
	}
	
	private static void init(String url, String author){
		
		InputStream ins = null;
		try {
				ins = am.open("tomcat.cer");
		        //读取证书
		        CertificateFactory cerFactory = CertificateFactory.getInstance("X.509");  //问1
		        Certificate cer = cerFactory.generateCertificate(ins);
		        //创建一个证书库，并将证书导入证书库
		        KeyStore keyStore = KeyStore.getInstance("PKCS12", "BC");   //问2
		        keyStore.load(null, null);
		        keyStore.setCertificateEntry("trust", cer);

				//把咱的证书库作为信任证书库
		        SSLSocketFactory socketFactory = new SSLSocketFactory(keyStore);
				@SuppressWarnings("deprecation")
				Scheme sch = new Scheme("https", socketFactory, 8443);
				//完工
				httpclient = new DefaultHttpClient();
				httpclient.getConnectionManager().getSchemeRegistry().register(sch);
				
				post = new HttpPost(url);
				post.setHeader("Authorization", author);
		}catch (Exception e) {
			e.printStackTrace();
		} finally {
		        try {
					ins.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
		}
		
	}

	public static InputStream getInputStream(Context context, String url, String author){
		initContext(context);
		init(url, author);
		
		HttpResponse response = null;
		
		try {
			
			response = httpclient.execute(post);
			HttpEntity entity = response.getEntity();
			
			if (entity != null){
				is = entity.getContent();
			}
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		System.out.println("url = " + url);
		System.out.println("is = " + is);
		
		return is;
	} 
}
